<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入商品名称"
          clearable
          maxlength="35"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brandId">
        <el-select
          v-model="queryParams.brandId"
          placeholder="请选择品牌"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in brandList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标签" prop="labels">
        <el-select
          maxlength="25"
          v-model="queryParams.labels"
          placeholder=请选择标签
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="dict in labelOptions"
            :key="dict.labelKey"
            :label="dict.name"
            :value="dict.labelKey"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="上下架" prop="shelves">
        <el-select
          v-model="queryParams.shelves"
          placeholder="请输入上下架"
          clearable
          @keyup.enter.native="handleQuery"
        >
          <el-option label="上架" value= 1 />
          <el-option label="下架" value= 0 />
        </el-select>
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <treeselect v-model="queryParams.categoryId" :options="categoryOptions" :normalizer="normalizer" placeholder="选择分类"
                    style="width: 230px;"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:goods:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:goods:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:goods:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="商品ID" align="center" prop="id"/>
      <el-table-column label="商品名称" align="center" prop="name"/>
      <el-table-column label="缩略图" align="center" prop="thumbnail">
        <template slot-scope="scope">
          <el-image
            style="width: 63px; height: 63px; margin-left: 5px;"
            :src="scope.row.thumbnail">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="轮播图" align="center" prop="banners" width="300">
        <template slot-scope="scope">
          <el-image v-for="(item,index) in JSON.parse(scope.row.banners)"
                    style="width: 63px; height: 63px; margin-left: 5px;"
                    :src="item">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品描述" align="center" prop="description"/>
      <el-table-column label="商品价格" align="center" prop="price"/>
      <el-table-column label="品牌" align="center" prop="brandName"/>
      <el-table-column label="分类" align="center" prop="categoryName"/>
      <el-table-column label="标签" align="center" prop="labels" :formatter="labelFormat"/>
      <el-table-column label="库存" align="center" prop="inventory"/>
      <el-table-column label="单位" align="center" prop="companyName"/>
      <el-table-column label="默认排序" align="center" prop="sort"/>
      <el-table-column label="上下架" align="center" prop="shelves">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.shelves"
            active-color="#13ce66"
            inactive-color="#ff4949"
            :active-value="1"
            :inactive-value="0"
            @change="changeShelves(scope.row)">
          </el-switch>
        </template>
      </el-table-column>
         <!--<el-table-column label="创建人" align="center" prop="createTy"/>-->
         <!--      <el-table-column label="销量" align="center" prop="sales"/>
       <el-table-column label="重量(克)" align="center" prop="weight" />
       <el-table-column label="供应商id" align="center" prop="supplierId" />
       <el-table-column label="店铺ID" align="center" prop="shopId" />
      <el-table-column label="条形码" align="center" prop="barCode"/>
      <el-table-column label="" align="center" prop="speclist"/>
      <el-table-column label="" align="center" prop="speclabellist" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:goods:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:goods:remove']"
          >删除
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleInfo(scope.row)"
            v-hasPermi="['system:goods:remove']"
          >查看
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {listGoods, getGoods, delGoods, addGoods, updateGoods} from "@/api/erp/goods";
import {listBrand} from "@/api/erp/brand";
import {listCategory} from "@/api/erp/category";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listLabel} from "@/api/erp/label";

export default {
  name: "Goods",
  components: {Treeselect},
  data() {
    return {
      //品牌列表
      brandList:[],
      //分类列表
      categoryOptions: [],
      //标签列表
      labelOptions: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 选中数组names
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品信息表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        brandId: null,
        categoryId: null,
        type: null,
        labels: null,
        barCode: null,
      },
      // 表单参数
      form: {},
    };
  },
  created() {
    this.getList();
    this.getLabelList();
    this.getBrandList();
    this.getCategoryList();
  },
  methods: {

    //是否上架
    changeShelves(row) {
      updateGoods(row).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("切换成功");
          this.getList();
        }
      });
    },

    /*node分类节点*/
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },

    //获取分类列表
    getCategoryList() {
      let params = {};
      listCategory(params).then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },

    //查询品牌列表
    getBrandList() {
      let params = {};
      listBrand(params).then(response => {
        this.brandList = response.rows;
      });
    },

    //获取标签列表
    getLabelList() {
      let params = {};
      listLabel(params).then(response => {
        this.labelOptions = response.rows;
      });
    },

    //标签
    labelFormat(row, column) {
      if (row.labels == null) return "";
      let labels = JSON.parse(row.labels);
      let labelName = '';
      for (let label of labels) {
        for (let lableOne of this.labelOptions) {
          if (lableOne.labelKey == label) {
            if (labelName != '') {
              labelName += ","
            }
            labelName += lableOne.name;
          }
        }
      }
      return labelName;
    },

    /** 查询商品列表 */
    getList() {
      this.loading = true;
      console.log(this.queryParams.labels+"")
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        thumbnail: null,
        banners: null,
        description: null,
        sortDescription: null,
        price: null,
        brandId: null,
        categoryId: null,
        cost: null,
        type: null,
        details: null,
        labels: null,
        inventory: null,
        sales: null,
        weight: null,
        supplierId: null,
        shelves: null,
        shopId: null,
        sort: null,
        createTy: null,
        updateTime: null,
        createTime: null,
        barCode: null,
        speclist: null,
        speclabellist: null
      };
      this.resetForm("form");
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.names = selection.map(item => item.name)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({path: '/addGoods'});
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({path: '/editGoods', query: {id: row.id}});
    },

    /** 查看商品详情按钮操作 */
    handleInfo(row) {
      this.$router.push({path: '/infoGoods', query: {id: row.id}});
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      const names = row.name || this.names;
      this.$modal.confirm('是否确认删除商品"' + names + '"？').then(function () {
        return delGoods(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/goods/export', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

